package com.ykh.task;
import com.ykh.service.VideoService;
import com.ykh.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
@Slf4j
public class VideoPlayCountSyncTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoService videoService;

    /**
     * 定时更新视频的播放量和点赞量开始执行同步至数据库
     */
    @Scheduled(cron = "0 */5 * ? * *") // 每小时执行一次任务
    public void syncVideoPlayCount() {
        log.info("--------更新视频的播放量和点赞量定时任务开始执行------------");
        //获取集合
        Map<Object, Object> playCounts = redisTemplate.opsForHash().entries(Constant.VIDEO_PLAY_COUNT_KEY_PREFIX);
        Map<Object, Object> likeCounts = redisTemplate.opsForHash().entries(Constant.VIDEO_LIKE_COUNT_KEY_PREFIX);
        Map<Object, Object> commentCounts = redisTemplate.opsForHash().entries(Constant.VIDEO_COMMENT_COUNT_KEY_PREFIX);
        //遍历map, 更新对应视频的播放增量
        for (Map.Entry<Object, Object> entry : playCounts.entrySet()) {
            Integer videoId  = Integer.valueOf(entry.getKey().toString());
            Long playCount = Long.valueOf(entry.getValue().toString());
            //更新播放量
            if(videoId!=null && playCount!=0){
                videoService.updatePlayCount(videoId, playCount);
            }
        }
        log.info("--------播放量更新完毕------------");
        for (Map.Entry<Object, Object> entry : likeCounts.entrySet()) {
            Integer videoId  = Integer.valueOf( entry.getKey().toString());
            Long likeCount = Long.valueOf(entry.getValue().toString());
            //更新点赞量
            if(videoId!=null && likeCount!=0){
                videoService.updateLikeCount(videoId, likeCount);
            }
        }
        log.info("--------点赞量更新完毕------------");
        for (Map.Entry<Object, Object> entry : commentCounts.entrySet()) {
            Integer videoId  = Integer.valueOf( entry.getKey().toString());
            Long commentCount = Long.valueOf(entry.getValue().toString());
            //更新评论量
            if(videoId!=null && commentCount!=0){
                videoService.updateCommentCount(videoId, commentCount);
            }
        }
        log.info("--------评论量更新完毕------------");
        //更新后应移除redis中的播放和点赞增量
        redisTemplate.delete(Constant.VIDEO_PLAY_COUNT_KEY_PREFIX);
        redisTemplate.delete(Constant.VIDEO_LIKE_COUNT_KEY_PREFIX);
        redisTemplate.delete(Constant.VIDEO_COMMENT_COUNT_KEY_PREFIX);
        log.info("--------redis增量移除完毕------------");
    }
}